package com.sphd.beautysalon.activitys.order;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sphd.beautysalon.R;
import com.sphd.beautysalon.adapters.SureOrdersAdapter;
import com.sphd.beautysalon.base.BaseActivity;
import com.sphd.beautysalon.base.RestaurantUrl;
import com.sphd.beautysalon.info.CouponInfo;
import com.sphd.beautysalon.info.GreensInfo;
import com.sphd.beautysalon.info.LoginInfo;
import com.sphd.beautysalon.info.RestaurantInfo;
import com.sphd.beautysalon.info.VipInfo;
import com.sphd.beautysalon.presenter.SureOrderPresenterImpl;
import com.sphd.beautysalon.utils.AppManager;
import com.sphd.beautysalon.utils.Constant;
import com.sphd.beautysalon.view.SureOrderView;

import org.litepal.crud.DataSupport;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/*
*
* 下单
* */
public class SureOrdersActivity extends BaseActivity implements SureOrderView {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.coun_money)
    TextView counMoney;
    @BindView(R.id.pay_f)
    TextView payF;
    @BindView(R.id.my_list)
    RecyclerView myList;
    @BindView(R.id.btn_over)
    Button btnOver;
    Intent intent;
    Bundle bundle;
    LoginInfo loginInfo;
    RestaurantInfo restaurantInfo;
    SureOrdersAdapter sureOrdersAdapter;
    List<GreensInfo> greensInfos;
    VipInfo vipInfo;
    SureOrderPresenterImpl sureOrderPresenter;
    @BindView(R.id.my_ticket)
    LinearLayout myTicket;
    List<CouponInfo> cardInfos;
    View foodView;
    private double favorable = 0;
    private double allMoneyoney = 0;
    private double account = 0;
    double lastprice = 0;
    double cardmoney=0;
    double cashmoney=0;
    TextView userMoney, favorableMoney, realyMoney, cardMoney, cashMoney;
    private String gmtTime;
    private int COUPON=1;
    private int allNo=0;
    private int payType=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sure_orders);
        ButterKnife.bind(this);
        initView();

    }

    private void initView() {
        setTitleBar(toolbar, "确认下单");
        intent = getIntent();
        bundle = intent.getExtras();
        loginInfo= DataSupport.findLast(LoginInfo.class);
        greensInfos = (List<GreensInfo>) bundle.getSerializable(Constant.GREENSINFO);
        restaurantInfo = (RestaurantInfo) bundle.getSerializable(Constant.RESTAURANTSINFO);
        vipInfo = (VipInfo) bundle.getSerializable(Constant.VIPINFO);
        allNo=bundle.getInt(Constant.ALLNO);
        sureOrderPresenter = new SureOrderPresenterImpl(this);
        cardInfos = new ArrayList<>();

        initFootView();
        initAdapter();
        addData();
    }

    private void initFootView() {

        foodView = View.inflate(context, R.layout.foot_view_sure_order, null);
        userMoney = $(R.id.user_money, foodView);
        favorableMoney = $(R.id.favorable_money, foodView);
        realyMoney = $(R.id.realy_money, foodView);
        cardMoney = $(R.id.card_money, foodView);
        cashMoney = $(R.id.cash_money, foodView);
    }

    private void addData() {
        sureOrderPresenter.addData(RestaurantUrl.Httptitle + RestaurantUrl.CONFIRMORDER + "cgid=" +
                restaurantInfo.getId() + "&userPhone=" + ((vipInfo == null) ? "null" : vipInfo.getMem_phone()));
    }

    private void initAdapter() {
        setRecy(myList);
        sureOrdersAdapter = new SureOrdersAdapter(R.layout.item_sure, greensInfos);
        myList.setAdapter(sureOrdersAdapter);
        sureOrdersAdapter.addFooterView(foodView);
    }


    @Override
    public void recMoney(double account, String time) {
        this.account = account;
        this.gmtTime=time;
        initMoney();
    }

    private void initMoney() {
        if (vipInfo != null) {
            int men_geage = vipInfo.getMem_grade();
            if (men_geage == 0) {
                allMoneyoney = getMyAllMoney();
                lastprice = allMoneyoney-favorable;
                cardmoney=0;
                cashmoney=allMoneyoney-favorable;
            } else if (men_geage == 1) {
                allMoneyoney = getMyAllMoney();
                lastprice = (allMoneyoney - favorable) * restaurantInfo.getCg_discount() / 10;
                cardmoney=0;
                cashmoney=(allMoneyoney - favorable) * restaurantInfo.getCg_discount() / 10;
            } else if (men_geage == 2) {
                payF.setText("充值卡");
                payType=1;
                if (getMyAllMoney() <= account) {
                    allMoneyoney = getMyAllMoney();
                    lastprice = allMoneyoney-favorable;
                    cardmoney=allMoneyoney - favorable;
                    cashmoney=0;
                } else {
                    toast("您的余额不足，请及时充值");
                /*充值卡余额不足：（原价+运费-余额）*折扣率*/
                    allMoneyoney = getMyAllMoney();
                    lastprice = (allMoneyoney - favorable - account) * restaurantInfo.getCg_discount() / 10;
                    cardmoney=account;
                    cashmoney=(allMoneyoney - favorable - account) * restaurantInfo.getCg_discount() / 10;
                }
            }
        } else {
            allMoneyoney = getMyAllMoney();
            lastprice = allMoneyoney;
            cardmoney=0;
            cashmoney=allMoneyoney;
        }
        userMoney.setText(turn(allMoneyoney, Constant.DECIMAL_POINT));
        favorableMoney.setText(turn(favorable, Constant.DECIMAL_POINT));
        realyMoney.setText(turn(lastprice, Constant.DECIMAL_POINT));
        cardMoney.setText(turn(cardmoney, Constant.DECIMAL_POINT));
        cashMoney.setText(turn(cashmoney, Constant.DECIMAL_POINT));
    }

    private double getMyAllMoney() {
        double allMoney = 0;
        for (int i = 0; i < greensInfos.size(); i++) {
            allMoney = greensInfos.get(i).getBuyNo() * greensInfos.get(i).getDishes_price() + allMoney;

        }
        return allMoney;
    }

    @Override
    public void recCards(List<CouponInfo> cardInfos) {
        if (cardInfos.size() == 0) {
            myTicket.setVisibility(View.GONE);
        }else {
            this.cardInfos=cardInfos;
        }
    }

    @OnClick({R.id.my_ticket, R.id.btn_over})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.my_ticket:
                if (cardInfos.size() != 0) {
                    bundle.putDouble(Constant.ALLMONEY, allMoneyoney);
                    bundle.putSerializable(Constant.COUPONS, (Serializable) cardInfos);
                    bundle.putString(Constant.GMT, gmtTime);
                    intent.putExtras(bundle);
                    intent.setClass(context, SelectCouponsActivity.class);
                    startActivityForResult(intent, COUPON);
                }
                break;
            case R.id.btn_over:
                sureOrder();
                break;
        }
    }

    private void sureOrder() {
        Map<String, String> map = new HashMap<>();
        if (vipInfo != null) {
            map.put("userPhone", vipInfo.getMem_phone());
            if(vipInfo.getMem_name()!=null){
                map.put("username", vipInfo.getMem_name());
            }
            if(vipInfo.getMem_card()!=null){
                map.put("card", vipInfo.getMem_card());
            }
        } else {
            map.put("username", restaurantInfo.getCg_name());
            map.put("userPhone", "null");
            map.put("card", "null");
        }
        map.put("staffphone", loginInfo.getStaff_phone());
        map.put("uid", String.valueOf(restaurantInfo.getId()));
        map.put("sumDishNumber", String.valueOf(allNo));
        map.put("realprice", realyMoney.getText().toString());
        map.put("vipprice", String.valueOf(getVipMoney()));
        map.put("lastprice", cashMoney.getText().toString());
        map.put("payType", String.valueOf(payType));
        map.put("isosale", 0 + "");
        map.put("ticket", favorable + "");
        if (cardInfos.size() != 0) {
            map.put("cards", getCardids());
        } else {
            map.put("cards", "[]");
        }
        map.put("sendInfo", "{" + "\"user_name\":\"" + null + "\",\"user_phone\":\"" + null + "\",\"addr\":\"" + null + "\"}");
        map.put("restrauntInfo", restrauntInfo());
        map.put("dishes", getAllDishes().toString());
        sureOrderPresenter.sendMap(map);
    }
    private StringBuffer getAllDishes() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("[");
        for (int i = 0; i < greensInfos.size(); i++) {
            buffer.append("{");
            buffer.append("\"dishes_no\":\"");
            buffer.append(greensInfos.get(i).getDishes_no());
            buffer.append("\",\"buyNum\":\"");
            buffer.append(greensInfos.get(i).getBuyNo());
            buffer.append("\",\"dishes_price\":\"");
            buffer.append(greensInfos.get(i).getDishes_price());
            buffer.append("\",\"dishes_vipprice\":\"");
            buffer.append(greensInfos.get(i).getDishes_vipprice());
            buffer.append("\",\"dishes_name\":\"");
            buffer.append(greensInfos.get(i).getDishes_name());
            buffer.append("\",\"dishes_pic\":\"");
            buffer.append(greensInfos.get(i).getDishes_pic());
            buffer.append("\"}");
            if (i != greensInfos.size() - 1) {
                buffer.append(",");
            }
        }
        buffer.append("]");
        return buffer;
    }
    private String restrauntInfo() {
        return "{" + "\"id\":\"" + restaurantInfo.getId() +
                "\",\"cg_name\":\"" + restaurantInfo.getCg_name() + "\",\"cg_phone\":\"" + restaurantInfo.getCg_phone() + "\"}";
    }

    private String getCardids() {
        StringBuffer buffer = new StringBuffer();
        List<CouponInfo> chooseId = new ArrayList<>();
        for (CouponInfo couponInfo : cardInfos) {
            if (couponInfo.isChecked()) {
                chooseId.add(couponInfo);
            }
        }
        if (chooseId.size() != 0) {
            buffer.append("[");
            for (int i = 0; i < chooseId.size(); i++) {
                buffer.append("{");
                buffer.append("\"id\":\"");
                buffer.append(chooseId.get(i).getId());
                buffer.append("\"}");
                if (i != chooseId.size() - 1) {
                    buffer.append(",");
                }
            }
            buffer.append("]");
        } else {
            buffer.append("[]");
        }
        return buffer.toString();
    }

    private double getVipMoney() {
        double allMoney = 0;
        for (int i = 0; i < greensInfos.size(); i++) {
            allMoney = greensInfos.get(i).getBuyNo() * greensInfos.get(i).getDishes_vipprice() + allMoney;
        }
        return allMoney;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == COUPON) {
            cardInfos = (List<CouponInfo>) data.getSerializableExtra("newcoupons");
            favorable = data.getDoubleExtra("money", 0);
            counMoney.setText("已优惠" + turn(favorable, Constant.DECIMAL_POINT) + "元");
            initMoney();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void recOk() {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                SureOrdersActivity.this);
        alertDialogBuilder
                .setTitle("提示")
                .setMessage("下单成功")
                .setCancelable(false)
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                AppManager.getAppManager().finishActivity(WaiterAddOrdersActivity.class);
                                intent.setClass(SureOrdersActivity.this, WaiterAddOrdersActivity.class);
                                startActivity(intent);
                                dialog.dismiss();
                                finish();
                            }
                        });
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    @Override
    public void recFaile() {
        toast("下单失败，请重试！");
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void dissLoading() {
        dissLoadingDialog();
    }
}
